<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div style="width: 1000px;padding:40px;margin: 100px auto 100px auto;border: 1px solid #C9C9C9;">
    <div style="margin-bottom: 10px;">聊天室</div>
    <textarea id="content" style="width: 100%;height: 300px;resize:none;"></textarea>
    <textarea id="message" style="width: 100%;height: 100px;resize:none;margin-top:-6px;border-top: none;"></textarea>
    <div style="text-align: right;">
        <button id="send" style="margin-top: 10px;">发送/[Enter]</button>
    </div>
</div>

<script type="text/javascript">

    var websocket = null;

    function getQueryVariable(variable)
    {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] === variable){return pair[1];}
        }
        return null;
    }

    //将消息显示在网页上
    function setMessage(newMessage) {
        var old = $('#content').val();
        $('#content').val(old + "\n" + newMessage);
    }

    function initWebSocket() {
        //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + window.location.host + "/websocket/chat");
        } else {
            alert('Not support websocket')
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessage("系统消息: 网络异常！");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {

        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessage(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessage("系统消息: 连接已断开！");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    }

    $(function () {
        initWebSocket();
        $("#send").click(function () {
            let message = $("#message").val();
            websocket.send(message);
            $("#message").val('');
        });

        $(document).keyup(function (event) {
            if (event.keyCode === 13) {
                $("#send").trigger("click");
            }
        });
    });
</script>
</body>
</html>